/**
 * author ：Peakmain
 * createTime：2024/9/19
 * mail:2726449200@qq.com
 * describe：Web组件注解管理类
 */
import { WebUrlBean } from '../../models/bean/web/WebUrlBean';
import { HandleResult } from '../../models/web/HandleReusult';

export const pathMethods: { [target: string]: { path: string, method: Function }[] } = {};

export const storedClass: { [key: string]: ((bean: WebUrlBean) => HandleResult)[] } = {};

// Handle decorator，用于将类名和方法路径映射到 storedClass
export function Handle(scheme: string, authority: string) {
  return function (target) {
    let classPathMethods = pathMethods[target.name];
    if (classPathMethods && classPathMethods.length > 0) {
      classPathMethods.forEach(pathResult => {
        //pk://onlineService/webPolicyAlert
        const fullPath =
          authority === '' ? scheme + "://" + pathResult.path : scheme + "://" + authority + pathResult.path;

        // 如果 storedClass 中已经有该路径，追加新的方法到数组中
        if (!storedClass[fullPath]) {
          storedClass[fullPath] = [];
        }
        // 将当前方法添加到该路径的数组中，确保方法返回 HandleResult
        const wrappedMethod = (...args: any[]) => {
          const result = pathResult.method(...args);
          if (result instanceof HandleResult) {
            return result;
          } else {
            return HandleResult.NOT_CONSUME;
          }
        };
        // 将当前方法添加到该路径的数组中
        storedClass[fullPath].push(wrappedMethod);
      });
    }
  };
}

// HandleMethod decorator，用于将类方法与路径绑定到 pathMethods
export function HandleMethod(path: string): MethodDecorator {
  return function (
      target,
      propertyKey: string,
      descriptor: PropertyDescriptor
  ): PropertyDescriptor {
    const className = target.constructor.name;
    console.log("mClassName:" + className);
    const originalMethod = descriptor.value;

    pathMethods[className] = pathMethods[className] || [];
    pathMethods[className].push({
      path: path,
      method: originalMethod
    });

    // 拦截方法，防止方法直接执行
    descriptor.value = function (...args: any[]) {
      console.log(`Method ${propertyKey} is intercepted. Not executed yet.`);
      return HandleResult.NOT_CONSUME;
    };

    return descriptor;
  };
}
